package com.my.utils;

import cn.hutool.json.JSONUtil;

import com.my.result.Result;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//表示这个类为spring的bean
@Component
public class JwtFilter extends AuthenticatingFilter {

    @Autowired
    JwtUtils jwtUtils;

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
       /*在下面面那个方法里面调用执行登录方法后会调用这个createToken方法区把请求的头中获取token然后放入jwttoken中
        *然后在去执行subject.login(token);
        * 然后会去securityManager接口中的Subject login
        * 然后会去DelegatingSubject类（实现subject了）中调用 login方法，然后就看不懂了.............
        */
        System.out.println("=======================（JwtFilter中实现createToken方法返回AuthenticationToken）从请求的头中获取token然后放入jwttoken中==================================");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //用户输入用户名与密码之后，后端会返回一个jwt在header中
        /*
        用户现在要从这个header中获取token，然后进行登录处理

        * */
        String jwt = request.getHeader("Authorization");
        if(!StringUtils.hasText(jwt)) {
            return null;
        }
        //返回得到的token放入JwtToken中
        return new JwtToken(jwt);
    }

    //判断jwt是否有效？
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        System.out.println("==================================================判断jtw是否有效========================================");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String jwt = request.getHeader("Authorization");
        //如果不包含jwt 直接交给注解进行认证拦截 不需经过shiro
        if(!StringUtils.hasText(jwt)) {
            System.out.println(jwt+"==================================没有进行认证========================");
            return true;
        } else {
            //如果有jwtcurrentUser
            System.out.println("==================================有认证========================");
            // 校验jwt
            Claims claim = jwtUtils.getClaimByToken(jwt);
            //如果校验异常或者过期丢出异常
            if(claim == null || jwtUtils.isTokenExpired(claim.getExpiration())) {
                System.out.println(jwt+"==================================token失效========================");
                throw new ExpiredCredentialsException("token已失效，请重新登录");
            }

            // 执行登录
            System.out.println("===============JWTFILTER67行执行登录（）=====================================================");
           //相当于执行了subject.login(token);内部执行了这个
            return executeLogin(servletRequest, servletResponse);
        }
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        System.out.println("=======================jwtfilter失败登录执行===================================");
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        Throwable throwable = e.getCause() == null ? e : e.getCause();
        Result result = Result.fail(throwable.getMessage());
        String json = JSONUtil.toJsonStr(result);
        try {
            httpServletResponse.getWriter().print(json);
        } catch (IOException ioException) {

        }
        return false;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

        /*
         *因为在controlle之前会先进入这个filter所以在这里进行跨域解决处理
         *
         * 跨域处理
         * */
        System.out.println("==============JWTFILTER的preHandle方法97行的跨域处理===========================================");
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request, response);
    }
}
